package com.cw.lang.common.utils.context;

import java.util.Map;

import com.alibaba.ttl.TransmittableThreadLocal;
import com.google.common.collect.Maps;

/**
 * @author chenw
 * @version $$Id: ThreadContextStore.java, v 0.1 2018/9/19 下午2:15 chenw Exp $$
 */
public final class ThreadContextStore {

    private ThreadContextStore() {}

    private volatile ThreadContextStore threadContextStore;

    private TransmittableThreadLocal<Map<String, Object>> threadContext = new TransmittableThreadLocal<>();

    public static synchronized ThreadContextStore getInstance() {
        return new ThreadContextStore();
    }

    /**
     * 设置线程上下文键值
     *
     * @param key key
     * @param value value
     */
    public synchronized void set(final String key, final Object value) {
        Map<String, Object> map = threadContext.get();
        if (map == null) {
            map = Maps.newHashMap();
        }
        map.put(key, value);
        threadContext.set(map);
    }

    /**
     * 设置线程上下文键值
     *
     * @param key key
     */
    public synchronized void removeKey(String key) {
        Map<String, Object> map = threadContext.get();
        if (map == null) {
            map = Maps.newHashMap();
        }
        map.remove(key);
        threadContext.set(map);
    }

    /**
     * 获得线程上下文对应key的值
     *
     * @param key key
     * @return value
     */
    public synchronized Object get(String key) {
        Map<String, Object> map = threadContext.get();
        if (map == null) {
            return null;
        } else {
            return map.get(key);
        }
    }

    /**
     * 清除线程上下文
     */
    public synchronized void clean() {
        Map<String, Object> map = threadContext.get();
        if (map != null) {
            map.clear();
            threadContext.set(map);
        }
    }
}
